package com.zzu.base.config;

import com.zzu.base.scheduler.config.JobConfig;
import com.zzu.base.scheduler.SpringBeanJobFactory;
import jakarta.annotation.Resource;
import org.quartz.Scheduler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class QuartzConfig {

    @Resource
    private DataSource dataSource;  // 注入Spring管理的Druid数据源
    @Resource
    private SpringBeanJobFactory springBeanJobFactory;

    @Resource
    private JobConfig jobConfig;
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();

        // 关键：将Spring的数据源设置给Quartz
        factory.setDataSource(dataSource);
        factory.setJobFactory(springBeanJobFactory);

        // 设置Quartz的配置属性（从application.yml中读取）
        Properties properties = new Properties();
        properties.setProperty("org.quartz.jobStore.dataSource", "default");
        properties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
        properties.setProperty("org.quartz.jobStore.tablePrefix", "QRTZ_");
        properties.setProperty("org.quartz.jobStore.isClustered", "false");
        properties.setProperty("org.quartz.scheduler.instanceName", "quartz-scheduler");
        properties.setProperty("org.quartz.scheduler.instanceId", "NON_CLUSTERED");
        properties.setProperty("org.quartz.threadPool.threadCount", "5");
        factory.setQuartzProperties(properties);

        // 其他可选配置：如启动延迟、作业工厂等

        return factory;
    }

    // 暴露Scheduler供业务调用（可选）
    @Bean
    public Scheduler scheduler() throws Exception {
        Scheduler scheduler= schedulerFactoryBean().getScheduler();
        return scheduler;
    }
}